<template>
  <div class="container">
    <div class="top">
      <div>
        <span>
          <span>水库名称：&nbsp;&nbsp;</span>
          <el-input v-model="searchData.name" style="width: 240px" />
        </span>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <el-button type="primary" plain @click="search">查询</el-button>
        <el-button type="primary" plain @click="resetSearch">重置</el-button>
      </div>
      <div>
        <el-button type="primary" @click="handleImport">导入</el-button>
        <el-button type="primary" @click="handleExport">导出</el-button>
        <el-button type="primary" @click="addData">新增</el-button>
      </div>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" height="calc(100% - 20px)">
      <el-table-column type="index" label="序号" width="55"> </el-table-column>
      <el-table-column prop="name" label="水库名称"> </el-table-column>
      <el-table-column prop="kilometer" label="公里标"> </el-table-column>
      <el-table-column label="水库位置">
        <template #default="scope">{{ scope.row.lon + "," + scope.row.lat }}
        </template>
      </el-table-column>
      <el-table-column prop="reach" label="影响范围"> </el-table-column>
      <el-table-column prop="capacity" label="设计容量(m3)"> </el-table-column>
      <el-table-column prop="waterStorage" label="现蓄水量(m3)"> </el-table-column>
      <el-table-column prop="contacts" label="联系人"> </el-table-column>
      <el-table-column prop="contactsPhone" label="联系电话"> </el-table-column>
      <el-table-column prop="remark" label="备注"> </el-table-column>
      <el-table-column prop="date" label="操作">
        <template #default="scope">
          <el-icon title="编辑" @click="edit(scope.row)">
            <Edit />
          </el-icon>
          &nbsp;
          <el-icon title="删除" @click="del(scope.row)">
            <Delete />
          </el-icon>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增对话框 -->
    <el-dialog title="水库信息详情" v-model="open" width="600px" append-to-body>
      <el-form ref="postRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="水库名称" prop="name">
          <el-input v-model="form.name" placeholder="水库名称" />
        </el-form-item>
        <el-form-item label="公里标" prop="kilometer">
          <el-input v-model="form.kilometer" placeholder="公里标" />
        </el-form-item>
        <!-- <div style="display: flex;justify-content: space-around"> -->
          <!-- <div style="width: 100px;">水库位置：</div> -->
          <el-form-item label="水库经度位置" prop="lon">
            <el-input-number v-model="form.lon" />
          </el-form-item>
          <el-form-item label="水库纬度位置" prop="lat">
            <el-input-number v-model="form.lat" />
          </el-form-item>
        <!-- </div> -->
        <el-form-item label="影响范围" prop="reach">
          <el-input v-model="form.reach" placeholder="请输入影响范围" />
        </el-form-item>
        <el-form-item label="设计容量(m3)" prop="waterStorage">
          <el-input-number v-model="form.capacity" :min="0" />
        </el-form-item>
        <el-form-item label="现蓄水量(m3)" prop="waterStorage">
          <el-input-number v-model="form.waterStorage" :min="0" />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactsPhone">
          <el-input v-model="form.contactsPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ElMessage,
  ElMessageBox
} from 'element-plus'
import {
  getReservoir,
  delReservoir,
  addReservoir,
  editReservoir,
} from "@/api/work";
const {
  proxy
} = getCurrentInstance();

const open = ref(false)
const loading = ref(true);
const tableData = ref([])

function getList() {
  loading.value = true
  getReservoir().then(res => {
    tableData.value = res.rows
    loading.value = false
  })
}
getList()

const searchData = ref({
  name: ''
})

function search() {
  getReservoir(searchData.value).then(res => {
    tableData.value = res.rows
  })
}
function resetSearch() {
  searchData.value = {
    name: ''
  }
  getList()
}

function addData() {
  open.value = true
  form.value = {}
}

import { getToken } from '@/utils/auth'
/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/sjgtw-emergency/reservoir/importData',
})
/** 导入按钮操作 */
function handleImport() {
  upload.title = '导入'
  upload.open = true
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs['uploadRef'].submit()
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download('sjgtw-emergency/reservoir/downloadTemplate', {}, `template_${new Date().getTime()}.xlsx`)
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].handleRemove(file)
  if (response.code == 200) {
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
  } else {
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + '</div>', '导入失败', { dangerouslyUseHTMLString: true })
  }
  getList()
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("sjgtw-emergency/reservoir/export", {
    ...queryParams.value,
  }, `水库分布管理${new Date().getTime()}.xlsx`);
}

function edit(row) {
  open.value = true
  form.value = JSON.parse(JSON.stringify(row))
  form.value.kilometer = kmUnit(form.value.kilometer)

}
function kmUnit(K) {
  console.log(K);
  
  var arr0 =[];
  if (K.indexOf("+") != -1 ) {
      arr0 = K.split("+");
      arr0[0] = subStringK(arr0);
      return  Number(arr0[0]) +"." +arr0[1].toString();
    }else if(K.indexOf("+") == -1 ){
      arr0 = subStringK([K]);
      return  Number(arr0[0])
    }
}
function subStringK(row) {
  return row[0].substring(1, row[0].length);
}
function del(data) {
  ElMessageBox.confirm(
    '确认删除吗？',
    'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }
  )
    .then(() => {
      delReservoir(data.id).then(res => {
        ElMessage({
          type: 'success',
          message: '已删除',
        })
        getList()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    postCode: undefined,
    postName: undefined,
    phone: undefined,
    kilometer: undefined
  },
  rules: {
    contactsPhone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
    // postName: [{ required: true, message: "岗位名称不能为空", trigger: "blur" }],
    // postCode: [{ required: true, message: "岗位编码不能为空", trigger: "blur" }],
    // postSort: [{ required: true, message: "岗位顺序不能为空", trigger: "blur" }],
  }
});
const {
  queryParams,
  form,
  rules
} = toRefs(data);

function cancel() {
  open.value = false
}

function submitForm() {
  proxy.$refs["postRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        editReservoir(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList()
        });
      } else {
        addReservoir(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList()
        });
      }
    }
  });
}
</script>

<style lang='scss' scoped>
.container {
  height: 100%;
  width: 100%;
  padding: 20px;
}

.top {
  height: 40px;
  line-height: 40px;
  display: flex;
  justify-content: space-between;
}

.end {
  justify-content: flex-end;
}

:deep(.el-table .el-table__cell) {
  text-align: center;
}

:deep(.el-table--border::before) {
  width: 0px;
  ;
}

:deep(.el-table--border::after) {
  width: 0px;
  ;
}
:deep(.el-input-number) {
  width: 100%;
  ;
}
</style>